<template>
  <div class="dynamic-form-container">
    <el-form ref="formRef" :disabled="isDisabled" :model="formData" :rules="rules" label-width="100px">
      <!-- 遍历所有行 -->
      <div
        v-for="(row, rowIndex) in groupedComponents"
        :key="rowIndex"
        class="margin-bottom-sm"
        :class="{ 'full-width-row': isFullWidthRow(row) }"
      >
        <!-- 遍历行中的组件 -->
        <el-form-item
          v-for="component in row"
          :key="component.rowIndex"
          :label="component.label"
          :prop="component.key"
          :required="(component.validate && component.validate.required) || false"
        >
          <!-- 根据不同类型渲染不同的表单控件 -->
          <template v-if="component.type === 'textfield'">
            <el-input
              v-model="formData[component._normalizedKey]"
              clearable
            />
          </template>

          <template v-else-if="component.type === 'number'">
            <el-input-number
              v-model.number="formData[component._normalizedKey]"
              controls-position="right"
              class="el-input-number-width"
              clearable
            />
          </template>

          <template v-else-if="component.type === 'textarea'">
            <el-input
              v-model="formData[component._normalizedKey]"
              type="textarea"
              :rows="3"
              clearable
            />
          </template>

          <template v-else-if="component.type === 'select'">
            <el-select
              v-model="formData[component.key]"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="item in component.values"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </template>
          <template v-else-if="['image', 'filepicker'].includes(component.type)">
            <!-- 文件上传, 图片显示 -->
            <el-form-item
              v-if="['image', 'filepicker'].includes(component.type)"
              :prop="component.key"
              :span="24"
              :rules="component.validate && component.validate.required ? [{ required: true, message: `请上传${component.label}`, trigger: 'blur' }] : []"
            >
              <Upload v-model="formData[component.key]" :file-list="fileList" accept=".jpg,.jpeg,.png,.bmp,.JPG,.JPEG,.PNG,.BMP,pdf,.PDF" :max-size="10" :limit="10" file-type="file" list-type="text" class="upload-demo" btn-text="添加附件" value-format="Object" />
            </el-form-item>
          </template>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { useRoute } from 'vue-router'
import Upload from '@/components/Upload'
import { ElMessage } from 'element-plus'

const props = defineProps({
  formConfig: {
    type: Object,
    required: true
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

const route = useRoute()
const formRef = ref(null)
const formData = ref({})
const fileList = ref([])
const rules = ref({})

// 将组件按行分组，每行最多3个
const groupedComponents = computed(() => {
  const components = props.formConfig.components || []
  const result = []
  if (!components) return []
  for (let i = 0; i < components.length; i += 3) {
    const row = components.slice(i, i + 3)
    // 检查这一行是否包含需要单独占一行的组件
    const hasFullWidth = row.some(comp => isFullWidthComponent(comp))

    if (hasFullWidth) {
      // 如果这一行有需要单独占一行的组件，则每个组件单独一行
      row.forEach(comp => {
        result.push([comp])
      })
    } else {
      // 否则正常一行显示3个
      result.push(row)
    }
  }

  return result
})

// 判断是否禁用表单
const isDisabled = computed(() => {
  return !(route.query.isEdit === 'true')
})

// 判断组件是否需要单独占一行
function isFullWidthComponent(component) {
  return ['image', 'textarea', 'filepicker', 'textfield', 'number', 'select'].includes(component.type)
}

// 判断行是否需要单独占一行（行中任意一个组件需要单独占一行）
function isFullWidthRow(row) {
  return row.length === 1 && isFullWidthComponent(row[0])
}

function initializeFormData() {
  formData.value = {}
  rules.value = {}
  const keyMap = new Map()
  console.log('初始化表单数据:======', props.formConfig)

  props.formConfig.components.forEach((component, index) => {
    let key = component.key

    // 处理重复的 key
    if (key && keyMap.has(key)) {
      key = `${key}_${index}`
      console.warn(`发现重复的 key: ${component.key}，已重命名为 ${key}`)
    }

    if (key) {
      keyMap.set(key, true)
      // 设置初始值
      let initialValue
      switch (component.type) {
        case 'number':
          initialValue = component[key] || 0
          break
        case 'filepicker':
        case 'image':
          initialValue = component[key] || []
          break
        default:
          initialValue = component[key] || ''
      }
      // 使用响应式赋值
      formData.value[key] = initialValue
      // 存储修正后的 key 到组件中
      component._normalizedKey = key

      // 设置验证规则
      if (component?.validate?.required) {
        rules.value[key] = [
          {
            required: true,
            message: `${component.label || key}不能为空`,
            trigger: ['blur', 'change']
          }
        ]

        // 特定字段的验证规则
        if (component.key === 'amount') {
          rules.value[key].push({
            type: 'number',
            message: `${component.label || key}必须为数字值`,
            trigger: ['blur', 'change']
          })
          rules.value[key].push({
            validator: (rule, value, callback) => {
              if (!value && value !== 0) {
                callback(new Error(`${component.label || key}不能为空`))
              } else {
                callback()
              }
            },
            trigger: ['blur', 'change']
          })
        }
      }
    }
  })
}

function checkComponent() {
  return new Promise((resolve, reject) => {
    formRef.value.validate((valid) => {
      valid ? resolve() : reject()
    })
  })
}

// 获取表单数据
function getComponnetValue() {
  const data = { ...formData.value }
  console.log('验证通过，表单数据:', formData.value, data)
  return data
}

// 文件上传处理
function handleFileChange(file, fileList, componentKey) {
  fileList.value[componentKey] = [file]
  formData.value[componentKey] = file.raw
}

// 图片上传处理
function handleImageSuccess(res, file, componentKey) {
  // 这里假设返回的res包含图片URL
  // 实际项目中需要根据后端API调整
  formData.value[componentKey] = URL.createObjectURL(file.raw)
}

// 图片上传前校验
function beforeImageUpload(file) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }

  return isJPG && isLt2M
}

watch(() => props.formConfig, () => {
  if (!props.formConfig || !props.formConfig.components) {
    return
  }
  initializeFormData()
}, { immediate: true });

defineExpose({
  checkComponent,
  getComponnetValue
});
</script>

<style lang="scss" scoped>
.dynamic-form-container {
  width: 50%;
  height: 100%;
  padding: 20px;
}

::deep .form-row .el-form-item {
  flex: 1;
  margin-right: 20px;
  margin-bottom: 0;
}

::deep .form-row .el-form-item:last-child {
  margin-right: 0;
}

.full-width-row {
  display: block;
}

::deep .full-width-row .el-form-item {
  display: block;
  width: 100%;
  margin-right: 0;
}

.image-container {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.preview-image {
  max-width: 200px;
  max-height: 200px;
  margin-bottom: 10px;
}

.upload-demo {
  display: inline-block;
}
.el-input-number-width{
  width: 50%;
}
</style>
